package date_202403

import (
	"regexp"
	"strconv"
)

func calculate(s string) int {

	itemRegexp := regexp.MustCompile("\\d+|[+\\-*/]")
	calculateItems := itemRegexp.FindAllString(s, -1)

	preSign := "+"
	valuesStack := make([]int, 0, len(calculateItems))
	for _, item := range calculateItems {
		num, err := strconv.Atoi(item)
		if err == nil {
			if preSign == "-" {
				valuesStack = append(valuesStack, -num)
			} else if preSign == "+" {
				valuesStack = append(valuesStack, num)
			} else if preSign == "*" {
				valuesStack[len(valuesStack)-1] = valuesStack[len(valuesStack)-1] * num
			} else if preSign == "/" {
				valuesStack[len(valuesStack)-1] = valuesStack[len(valuesStack)-1] / num
			}
		}
		if item == "+" || item == "-" || item == "*" || item == "/" {
			preSign = item
		}
	}

	sum := 0
	for _, v := range valuesStack {
		sum += v
	}
	return sum
}
